# -*- coding:utf-8 -*-
import inspect
from importlib import import_module
from flask_script import Command
from flask import Blueprint
from redis import StrictRedis


def load_config(config_path):
    """自动加载配置"""
    # import module 根据字符串路径直接进行模块导包，识别模块中的变量成员
    module = import_module(config_path)
    config_file_name = config_path.split(".")[-1]
    if config_file_name == "settings":
        return module.InitConfig
    return module.Config


def load_command(manager,command_path):
    """自动加载命令"""
    module = import_module(command_path)
    # 搜索当前模块下的所有类
    class_list = inspect.getmembers(module,inspect.isclass)
    for class_name, class_object in class_list:
        if issubclass(class_object, Command) and class_name != "Command":
            manager.add_command(class_object.name, class_object)


def path(url, view_func, **kwargs):
    """注册路由"""
    return {"rule": url, "view_func": view_func, **kwargs}


def include(url, blueprint_path):
    return {"url_prefix": url, "path": blueprint_path}


def load_blueprint(app, db):
    """自动加载蓝图"""
    app_url_list = import_module(app.config.get("URL_PATH")).urlpatterns
    for blueprint_path in app.config.get("INSTALLED_APPS"):
        # 获取蓝图名称
        blueprint_name = blueprint_path.split(".")[-1]
        for blueprint_url in app_url_list:
            if blueprint_url.get("path") == blueprint_name + ".urls":
                url_prefix = blueprint_url.get("url_prefix")
                break
        # 创建蓝图对象
        blue = Blueprint(blueprint_name, blueprint_path)
        # 蓝图对象自动注册路由
        blue_urls_module = import_module(blueprint_path + ".urls")
        for urls_item in blue_urls_module.urlpatterns:
            blue.add_url_rule(**urls_item)
        # 注册蓝图
        app.register_blueprint(blue, url_prefix=url_prefix)
        # 加载当前蓝图下的模型
        model_module = import_module(blueprint_path+".models")

        # model_list = inspect.getmembers(model_module, inspect.isclass)
        # for model_name, model_object in model_list:
        #     if issubclass(model_object, db.Model) and model_name != "Model":
        #         manager.add_command(model_object.name, model_object)


def load_redis(app):
    redis_host = app.config.get("REDIS_HOST")
    redis_port = app.config.get("REDIS_PORT")
    redis_db = app.config.get("REDIS_DB")
    # decode_responses=True, 返回的数据自动把字节流转换为数据
    if all([redis_host, redis_port, str(redis_db)]):
        return StrictRedis(host=redis_host, port=redis_port, db=redis_db, decode_responses=True)
    elif redis_host and not redis_port and not str(redis_db):
        return StrictRedis(host=redis_host, port=6379, db=0, decode_responses=True)
    elif redis_host and redis_port and not redis_db:
        return StrictRedis(host=redis_host, port=redis_port, db=0, decode_responses=True)
    else:
        return None

